<template>
  <div class="login-container">
    <div class="login-box">
      <h2 class="login-title">用户登录</h2>

      <div class="login-mode" v-if="false">
        <button :class="['mode-btn', { active: loginMode === 'account' }]" @click="switchLoginMode('account')">
          <el-icon>
            <User />
          </el-icon> 账号登录
        </button>
        <button :class="['mode-btn', { active: loginMode === 'email' }]" @click="switchLoginMode('email')">
          <el-icon>
            <Message />
          </el-icon> 邮箱登录
        </button>
      </div>

      <el-form ref="loginFormRef" :model="formData" :rules="rules" @keyup.enter="handleSubmit" class="login-form">
        <div v-if="loginMode === 'account'">
          <el-form-item prop="username">
            <el-input v-model="formData.username" size="large" placeholder="请输入用户名" prefix-icon="User" clearable />
          </el-form-item>

        </div>
        <div v-else>
          <el-form-item prop="email">
            <el-input v-model="formData.email" size="large" placeholder="请输入邮箱" prefix-icon="Message" clearable />
          </el-form-item>
          <!-- <el-form-item prop="code">
            <el-input v-model="formData.code" size="large" type="text" placeholder="请输入验证码" prefix-icon="Lock"
              clearable>
              <template #append>
                <div class="code-btn">
                  <el-button v-show="sendTime === 60" type="primary" size="small" @click="sendCode">发送验证码</el-button>
                  <el-button v-show="sendTime < 60" type="primary" disabled size="small" @click="sendCode">
                    {{ sendTime }}
                  </el-button>
                </div>
              </template>
</el-input>
</el-form-item> -->
        </div>

        <el-form-item prop="password">
          <el-input v-model="formData.password" size="large" type="password" placeholder="请输入密码" prefix-icon="Lock"
            show-password clearable />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" class="login-btn" :loading="loading" @click="handleSubmit">
            登录
          </el-button>
        </el-form-item>
      </el-form>

      <div class="login-links">
        <el-link type="primary" @click="gotoRegister">注册账号</el-link>
        <el-link type="primary" @click="gotoForgetPassword">忘记密码</el-link>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, type FormInstance, type FormRules } from "element-plus";
import { useUserStore } from "@/store/user";
import type { LoginFormData } from "@/types/auth";

const router = useRouter();
const userStore = useUserStore();
const loginFormRef = ref<FormInstance>();

const formData = ref<LoginFormData>({
  username: "",
  password: "",
  email: "",
  code: "",
});

// 账户类型
let loginMode = ref<"account" | "email">("email");
const switchLoginMode = (mode: "account" | "email") => {
  loginMode.value = mode;
};

const rules = ref<FormRules<LoginFormData>>({
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    { min: 3, max: 20, message: "长度在 3 到 20 个字符", trigger: "blur" },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, max: 20, message: "长度在 6 到 20 个字符", trigger: "blur" },
  ],
  email: [
    { required: true, message: "请输入邮箱", trigger: "blur" },
    {
      type: "email",
      message: "请输入有效的邮箱地址",
      trigger: ["blur", "change"],
    },
  ],
  code: [
    { required: true, message: "请输入验证码", trigger: "blur" },
    { min: 6, max: 6, message: "验证码为6位数字", trigger: "blur" },
  ],
});

const loading = ref(false);

// 发送验证码
// 60秒内只能发送一次
let sendTime = ref(60);
// 倒计时函数
const sendCountdown = () => {
  if (sendTime.value > 0) {
    sendTime.value--;
    setTimeout(sendCountdown, 1000);
  } else {
    sendTime.value = 60; // 重置倒计时
  }
};
const sendCode = async () => {
  try {
    if (loginMode.value !== "email") {
      ElMessage.warning("请切换到邮箱登录模式");
      return;
    }
    if (!formData.value.email) {
      ElMessage.error("请输入邮箱地址");
      return;
    }
    loading.value = true;
    await userStore.sendEmailCode({
      email: formData.value.email,
      sendType: "2",
    });
    ElMessage.success("验证码已发送，请查收");
    sendCountdown();
  } catch (error) {
    if (error instanceof Error) {
      ElMessage.error(error.message || "发送验证码失败");
    }
  } finally {
    loading.value = false;
  }
};

const handleSubmit = async () => {
  try {
    // 验证表单
    await loginFormRef.value?.validate();

    loading.value = true;
    await userStore.login({
      ...formData.value,
      loginType: loginMode.value,
    });

    ElMessage.success("登录成功");
    router.push("/calendar");
  } catch (error) {
    console.log('Login error:', error);
  } finally {
    loading.value = false;
  }
};

const gotoRegister = () => {
  router.push("/register");
};

const gotoForgetPassword = () => {
  router.push("/forget");
};
</script>

<style lang="scss" scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f5f5f5;
  background-image: url("/source/png/bg.png");
  background-repeat: no-repeat;
  background-size: cover;

  .login-box {
    width: 90%;
    max-width: 400px;
    padding: 30px;
    margin: 20px 0;
    background: rgba(255, 255, 255, 0.9);
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

    .login-title {
      text-align: center;
      margin-bottom: 30px;
      color: #2c3e50;
      font-size: 28px;
      font-weight: 600;
      position: relative;
      padding-bottom: 15px;

      &::after {
        content: "";
        position: absolute;
        bottom: 0;
        left: 50%;
        transform: translateX(-50%);
        width: 80px;
        height: 4px;
        background: linear-gradient(to right, #3498db, #e2aa93);
        border-radius: 2px;
      }
    }

    .login-mode {
      display: flex;
      justify-content: center;
      margin-bottom: 25px;
      gap: 20px;
    }

    .mode-btn {
      padding: 10px 20px;
      border: none;
      background: transparent;
      font-size: 16px;
      font-weight: 500;
      color: #7f8c8d;
      cursor: pointer;
      border-radius: 30px;
      transition: all 0.3s ease;
      position: relative;


      display: flex;
      align-items: center;

      i {
        margin-right: 8px;
      }

      &.active {
        color: #3498db;
        background: rgba(52, 152, 219, 0.1);
      }
    }


    .login-form {
      margin-bottom: 20px;

      .el-form-item {
        padding-top: 3px;
      }

      .code-btn {
        min-width: 60px;
        text-align: center;
      }

      .login-btn {
        margin-top: 10px;
        width: 100%;
        height: 50px;
        border-radius: 12px;
        font-size: 16px;
        font-weight: 600;
        letter-spacing: 1px;
        background: linear-gradient(to right, #3498db, #e2aa93);
        border: none;
        transition: all 0.3s ease;
        box-shadow: 0 4px 15px rgba(52, 152, 219, 0.3);

        &:hover {
          box-shadow: 0 6px 20px rgba(52, 152, 219, 0.4);
        }
      }
    }

    .login-links {
      display: flex;
      justify-content: space-between;
      margin-top: 15px;
    }
  }
}
</style>
